const jwt = require("jsonwebtoken")
const db = require('./db')
db.init()
module.exports = async (req, res, next) => {
  if (req.method == "POST" && req.path == "/login") {
    //解构出传递过来的参数
    const { username, password } = req.body
    console.log(username,password);
    const tes = await db.checkUser(username,password)
    if (tes) {
      //校验通过，生成token，返回给前端  jwt.sign 根据用户名生成一段加密字符
      let token = jwt.sign({ username }, "2302B")
      console.log(token);
      return res.status(200).json({
        success: true,
        data: {
          token
        }
      })
    } else {
      //表明是登录接口
      return res.status(200).json({
        success: false,
        data: {}
      })
    }
  }
  if(req.method == "POST" && req.path == "/register"){
    const {username,password} = req.body
    console.log(username,password)
    const registerInfo = await db.register(username,password)
    console.log(registerInfo)
    return res.status(200).json({
      success:true,
      data:{
        ...registerInfo,
      }
    })
  }
    //请求头中获取token
     const token = req.headers["token"]
     //如果没有就会报错所以要抛出错误
     try {
       const decoded = jwt.verify(token,"2302B")
       console.log("解密token",decoded)
     } catch (error) {
       return res.status(200).json({
         success:false,
         msg:"token已失效"
       })
     }
  

  //所有的网络请求，都会被中间件拦截，在当前函数处理
  //不要忘记调用next() !!! (重点)
  next()
}